<template>
  <div class="p-1.5 box-border h-full">
    <div class="flex justify-between">
      <div>
        <a-form
            layout="inline"
            :model="searchState"
            @finish="getAllLog"
          >
            <a-form-item label="日期">
              <a-date-picker :value="searchState.Date" :disabled-date="disabledDate" @change="DateRangeChange"/>
            </a-form-item>
            <a-form-item>
              <a-button type="default" @click="ResetSearchState">重置</a-button>
              <a-button class="!ml-1.5" type="primary"  html-type="submit"> 查询  </a-button>
            </a-form-item>
          </a-form>
      </div>
    </div>
    <div :style="{height: `${windowHeight - 45}px`,width: '100%',overflow:'hidden'}">
      <div id="echarts" :style="{height: `${windowHeight - 45}px`}"></div>
    </div>
  </div>
</template>
<script setup>
import dayjs from "dayjs";
import { ref,onMounted,reactive,toRaw,onActivated, nextTick, watch } from 'vue';
import * as echarts from 'echarts/core';
import {
  DatasetComponent,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  TransformComponent
} from 'echarts/components';
import { LineChart } from 'echarts/charts';
import { LabelLayout, UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
import {ChartOptions} from "./chartData";
import { windowHeight,useDataLogBridge } from '../tools/index';
const searchState = reactive({
  Date:dayjs(),
  Page:1,
  PageSize:99999
});
const dataLogBridge = useDataLogBridge();
let timer = null;
const disabledDate = (current) => {
  return current && current > dayjs();
};

const ChartData = ref([]);

echarts.use([
  DatasetComponent,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  TransformComponent,
  LineChart,
  CanvasRenderer,
  LabelLayout,
  UniversalTransition
]);


const ResetSearchState = () => {
    ChartData.value = []
    searchState.Date = dayjs()
}
const DateRangeChange = (value,model)=>{
  ChartData.value = []
  searchState.Date = value;
}
//获取所有数据日志
const getAllLog = (date) => {
  const isValid = date?.isValid&&date?.isValid();
  if(!isValid){
    myChart.showLoading();
  }
  return new Promise(async(resolve,reject)=>{
    try {
    const result = await dataLogBridge.GetAllList(JSON.stringify({
      ...searchState,
      StartDate:isValid?`${date.format('YYYY-MM-DD HH:mm:ss')}`:`${searchState.Date.format('YYYY-MM-DD')} 10:00:00`,
      EndDate:isValid?`${date.format('YYYY-MM-DD')} 23:59:59`:`${searchState.Date.format('YYYY-MM-DD')} 23:59:59`
    }));
    myChart.hideLoading();
    const res = JSON.parse(result);
    if(res.code==0){
      ChartData.value = isValid?[...ChartData.value,...res.data.list]:[...res.data.list];
      if(isValid){
        nextTick(()=>{
           myChart.setOption({
              dataset:{
                dimensions: [
                    "createdAt",
                    "厂内温度",
                    "厂内湿度",
                    "固化炉测量温度",
                    "水分炉测量温度",
                    "粗洗喷淋泵压力值",
                    "精洗喷淋泵压力值",
                    "脱脂pH值",
                    "脱脂喷淋泵压力值",
                    "陶化pH值",
                    "陶化喷淋泵压力值"
                ],
                source:[...ChartData.value].reverse()
              },
          }, {
            notMerge: false,
            replaceMerge: ['dataset']
        });
        })
       
      }else{
        const options = ChartOptions([...ChartData.value].reverse())
        options.dataset.source = [...ChartData.value].reverse();
        nextTick(()=>{
          myChart?.setOption(options);
        })
      }
      resolve()
    }else{
      message.error(res.msg);
      reject()
    }
  } catch (error) {
    myChart.hideLoading();
      reject()
  }
  })
};

var option;
var myChart;

option && myChart.setOption(option);
onMounted(()=>{
  
var chartDom = document.getElementById('echarts');
  myChart = echarts.init(chartDom);
  getAllLog()
  timer&&clearInterval(timer);
  timer = setInterval(()=>{
    if(searchState.Date.format("YYYY-MM-DD") == dayjs().format("YYYY-MM-DD")&& ChartData.value.length){
      getAllLog(dayjs())
    }
  },1000)
})
onActivated(()=>{
  console.log("激活")
})

watch(()=>windowHeight.value,(newVal,oldVal)=>{
  myChart?.resize({
    height: newVal - 45
  })
})
</script>